package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IBankFinder;
import com.gears_software.sxdc.dccx.data.finder.IVouchersFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.CanUseVouchersModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.UserBalance;
import com.gears_software.sxdc.dccx.data.model.request.RBalanceTrading;
import com.gears_software.sxdc.dccx.data.model.request.RChargeModel;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.orhanobut.logger.Logger;
import com.pingplusplus.android.Pingpp;
import com.sdsmdg.tastytoast.TastyToast;
import com.gears_software.sxdc.dccx.R;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/9/27.
 * 支付界面的activity
 */
@EActivity(R.layout.activity_pay)
public class PayActivity extends Activity {
    private static String YOUR_URL = "http://218.244.151.190/demo/charge";
    public static final String CHARGE_URL = YOUR_URL;
    /**
     * 微信支付渠道
     */
    private static final String CHANNEL_WECHAT = "wx";
    /**
     * 支付宝支付渠道
     */
    private static final String CHANNEL_ALIPAY = "alipay";
    public static final boolean LIVEMODE = false;
    @App
    DCCXApplication app;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView tv_zhifubao_icon;
    @ViewById
    TextView tv_weixin_icon;
    @ViewById
    RadioGroup rg_zhifu;
    @ViewById
    RadioButton rb_zhifubao;
    @ViewById
    RadioButton rb_weixin;
    @ViewById
    Button btn_submit;
    @ViewById
    TextView tv_yu_e_icon;
    @ViewById
    TextView tv_money_count;
    @ViewById
    RadioButton rb_yu_e;
    @ViewById
    RelativeLayout re_youhui;
    @ViewById
    TextView txt_youhui;
    @ViewById
    TextView txt_right_icon;
    @Extra
    String type; //获取charge
    @Extra
    String orderid;
    @Extra
    String orderNo;
    @Extra
    String driverid;
    @Extra
    String tradingType;
    @Extra
    BigDecimal price;
    @Extra
    String voucherid;
    @Extra
    BigDecimal discountamount;
    @RestService
    IBankFinder bankFinder;
    @RestService
    IVouchersFinder vouchersFinder;
    @Bean
    GearsErrorHandler errorHandler;
    String clinetIp = "";
    int chanel = 1;

    RChargeModel chargeModel = new RChargeModel();
    RBalanceTrading balanceTrading = new RBalanceTrading();
    MaterialDialogProgress progress;
    OptionsPickerView pickerView;
    List<CanUseVouchersModel> vouchersModelList = new ArrayList<CanUseVouchersModel>();
    int RESULT_CODE = 0;

    @AfterViews
    void created() {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        initIconFont();
        bankFinder.setRestErrorHandler(errorHandler);
        vouchersFinder.setRestErrorHandler(errorHandler);
        Pingpp.DEBUG = true;
        if (type.equals("3")) {
            tv_money_count.setText(price.subtract(discountamount).toString());
            if (discountamount != null && !discountamount.equals("")) {
                if (discountamount.compareTo(new BigDecimal(0.00)) == 0) {
                    re_youhui.setVisibility(View.GONE);
                } else {
                    String youhui = String.format("%.2f", Float.parseFloat(discountamount.toString()));
                    re_youhui.setVisibility(View.VISIBLE);
                    txt_youhui.setText(youhui);
                }
            }
        } else if (type.equals("4")) {
            tv_money_count.setText(price.toString());

        }
        GetNetIp();
        progress = new MaterialDialogProgress(this);
    }

    void initIconFont() {
        actionbar_title.setText("支付");
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        right_icon.setVisibility(View.GONE);
        tv_zhifubao_icon.setTypeface(app.iconfont);
        tv_weixin_icon.setTypeface(app.iconfont);
        tv_yu_e_icon.setTypeface(app.iconfont);
        txt_right_icon.setTypeface(app.iconfont);
    }

    /**
     * 获取外网IP地址
     */
    @Background
    void GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                showResult(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @UiThread
    void showResult(String line) {
        clinetIp = line;
    }

    @Click
    void btn_submit() {
        progress.show("正在支付...");

        if (rb_zhifubao.isChecked()) {
            chanel = 1;
            chargeModel.setChannel(chanel);
            initCharge();
        } else if (rb_weixin.isChecked()) {
            chanel = 2;
            chargeModel.setChannel(chanel);
            initCharge();
        } else if (rb_yu_e.isChecked()) {
            balanceTrading.setOrderid(orderid);
            balanceTrading.setType(tradingType);
            balanceTrading.setDriverid(driverid);
            balanceTrading.setVoucherid(voucherid);
            getUserBalance();
//            TastyToast.makeText(this, "您选择了余额支付", app.SHORT, app.WARNING);
        } else {
            TastyToast.makeText(this, "请选择支付方式", app.SHORT, app.WARNING);
        }

    }

    private void initCharge() {
        btn_submit.setEnabled(false);
        chargeModel.setAmount(new BigDecimal(tv_money_count.getText().toString()).toString());
        chargeModel.setType(type);
        chargeModel.setChannel(chanel);
        chargeModel.setClientIp(clinetIp);
        chargeModel.setOrderNo(orderNo);
        chargeModel.setOrderid(orderid);
        chargeModel.setVoucherid(voucherid);
        getCharge();
    }


    @Background
    void getCharge() {
        ResultModel<String> res = bankFinder.getCharge(chargeModel);
        showChargeResult(res);
    }

    @UiThread
    void showChargeResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null && !res.getData().equals("")) {
                    String data = res.getData();
                    Pingpp.createPayment(this, data);
                }
            } else {
                btn_submit.setEnabled(true);
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
                btn_submit.setEnabled(true);
                if (progress != null) {
                    progress.dismiss();
                }
            }
        }
    }


    /**
     * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。
     * 最终支付成功根据异步通知为准
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (progress != null) {
            progress.dismiss();
        }
        btn_submit.setEnabled(true);
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                if (result != null && !result.equals("")) {
                     /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                    if (result.equals("success")) {
                        TastyToast.makeText(this, "支付成功", app.SHORT, app.SUCCESS);
                        RESULT_CODE = 1;

                    } else if (result.equals("fail")) {
                        RESULT_CODE = -1;
                        TastyToast.makeText(this, "支付失败", app.SHORT, app.ERROR);
                    } else if (result.equals("cancel")) {
                        RESULT_CODE = 2;
                        TastyToast.makeText(this, "您已取消支付", app.SHORT, app.WARNING);
                    } else if (result.equals("invalid")) {
                        RESULT_CODE = 3;
                        TastyToast.makeText(this, "末能安装应用", app.SHORT, app.WARNING);
                    }
                    Intent intent = new Intent();
                    intent.putExtra("resultCode", RESULT_CODE);
                    setResult(5, intent);
                    if (RESULT_CODE == 1) {
                        this.finish();
                    }
                } else {
                    String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                    String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                    TastyToast.makeText(this, errorMsg + errorMsg, app.SHORT, app.ERROR);
                }

            }
        }
    }

    @Background
    public void getUserBalance() {
        ResultModel<UserBalance> res = bankFinder.getUserBalance();
        showBalanceResult(res);
    }

    @UiThread
    void showBalanceResult(ResultModel<UserBalance> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    UserBalance balance = res.getData();
                    if (balance.getUseramount().compareTo(new BigDecimal(0)) == 1) {
                        balanceTrading(balanceTrading);
                    } else {
                        TastyToast.makeText(this, "当前余额为0,不能进行余额支付。", app.SHORT, app.ERROR);
                        if (progress != null) {
                            progress.dismiss();
                        }
                    }
                }
            }
        }
    }

    @Background
    void balanceTrading(RBalanceTrading balanceTrading) {
        ResultModel<String> res = bankFinder.balanceTrading(balanceTrading);
        showTradingResult(res);
    }

    @UiThread
    void showTradingResult(ResultModel<String> res) {
        if (progress != null) {
            progress.dismiss();
        }
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "余额支付成功", app.SHORT, app.SUCCESS);
                RESULT_CODE = 1;
                Intent intent = new Intent();
                intent.putExtra("resultCode", RESULT_CODE);
                setResult(5, intent);
                this.finish();
            } else {
                RESULT_CODE = -1;
                TastyToast.makeText(this, "余额支付失败", app.SHORT, app.ERROR);
            }
        }
    }


    @Click
    void re_youhui() {
        getCanUseList(price);
    }

    @Background
    void getCanUseList(BigDecimal factprice) {
        ResultModel<List<CanUseVouchersModel>> res = vouchersFinder.getCanUse(factprice);
        showCanUseResult(res);
    }

    @UiThread
    void showCanUseResult(ResultModel<List<CanUseVouchersModel>> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    vouchersModelList = res.getData();
                    if (vouchersModelList.size() > 0) {
                        pickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                String youhui = String.format("%.2f", Float.parseFloat(vouchersModelList.get(options1).getAmount().toString()));
                                String amount = price.subtract(vouchersModelList.get(options1).getAmount()).toString();
                                tv_money_count.setText(String.format("%.2f", Float.parseFloat(amount)));
                                txt_youhui.setText(youhui);
                                voucherid = vouchersModelList.get(options1).getId();
                            }
                        }).setContentTextSize(12).setLineSpacingMultiplier(2).build();
                        pickerView.setPicker(vouchersModelList);
                        pickerView.show();
                    }
                }
            }
        }
    }


    @Click
    void back_icon() {
        finish();
    }
}
